package com.apobates.forum.core.security.exposure.supply;

import com.apobates.forum.core.entity.BoardModerator;
import com.apobates.forum.core.entity.proxy.BoardModeratorReplica;
import com.apobates.forum.core.security.exception.VerificaFailException;
import com.apobates.forum.event.elderly.ForumActionEnum;
import com.apobates.forum.member.entity.Member;
import com.apobates.forum.member.entity.MemberRoleEnum;
import com.apobates.forum.utils.lang.TriPredicate;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.function.Supplier;
import java.util.stream.Stream;

/**
 * 版主身份扩展检测器
 * 
 * @author xiaofanku
 * @since 20200806
 */
public final class ModeratorPlugStrategy implements TriPredicate<Member, ForumActionEnum, Set<MemberRoleEnum>>{
    private final Supplier<Stream<BoardModeratorReplica>> moderators;
    
    public ModeratorPlugStrategy(Supplier<Stream<BoardModeratorReplica>> moderators) {
        this.moderators = moderators;
    }
    
    @Override
    public boolean test(Member member, ForumActionEnum action, Set<MemberRoleEnum> allowRoles) {
        if (MemberRoleEnum.ADMIN == member.getMrole()) { //为管理员放行
            return true;
        }
        if (allowRoles.containsAll(List.of(MemberRoleEnum.BM, MemberRoleEnum.MASTER))) {
            //是否是本版块的版主
            if (moderators == null) { //没有设版主
                throw new VerificaFailException("您的管理权限被拦截");
            }
            Optional<Long> rs = moderators.get().map(BoardModerator::getMemberId).filter(mid -> mid == member.getId()).findFirst();
            if (!rs.isPresent()) {
                throw new VerificaFailException("您暂不具备当前对象的管理权限");
            }
        }
        return true;
    }
}